<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\library\Auth;
use fast\Random;
use think\Db;
use think\Exception;

/**
 * 课程管理
 *
 * @icon fa fa-user
 */
class Card extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';
    protected $noNeedRight = ['open','close'];

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Card');
    }

    /**
     * 查看
     */
    public function index()
    {
        $this->relationSearch =true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $count = $this->model
                ->with(['Company'])
                ->where($where)
                ->count();
            $list = $this->model
                ->with(['Company'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset,$limit)
                ->select();
            foreach ($list as $w=>&$v){
            }
            $result = array("total" => $count, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            try {
                Db::startTrans();
                // 准备批量插入的数据
// 准备批量插入的数据
                $insertData = [];
                $baseTime = time(); // 基础时间戳（避免重复获取）
                $existingCodes = []; // 全局存储已生成的card_no，防止所有公司间重复
                $numPerCompany = $params['num']; // 每个公司需要生成的卡数量
                $companyIds = explode(',', $params['company_id']);
                $companyCount = count($companyIds);

// 校验公司ID和数量
                if ($companyCount === 0) {
                    $this->error("请指定公司ID");
                }
                if ($numPerCompany <= 0) {
                    $this->error("生成数量必须大于0");
                }

// 遍历每个公司，为其生成numPerCompany张卡
                foreach ($companyIds as $companyId) {
                    // 为当前公司生成指定数量的卡
                    for ($i = 0; $i < $numPerCompany; $i++) {
                        // 生成12位不重复的card_no（全局去重）
                        do {
                            $timePart = substr((string)$baseTime, -6); // 时间戳后6位
                            $randPart = str_pad(mt_rand(0, 999999), 6, '0', STR_PAD_LEFT); // 6位随机数补0
                            $cardNo = $timePart . $randPart;
                        } while (in_array($cardNo, $existingCodes));

                        $existingCodes[] = $cardNo;

                        // 组装当前公司的卡数据
                        $insertData[] = [
                            'company_id' => $companyId,
                            'card_no'    => $cardNo,
                            'money'      => $params['money'],
                            'createtime' => $baseTime,
                            'updatetime' => $baseTime,
                        ];
                    }
                }

                // 批量插入
                $res = $this->model->insertAll($insertData);
                if ($res) {
                    Db::commit();
                    $this->success("生成成功", '', ['count' => $res]);
                }

                Db::rollback();
                $this->error("生成失败");

            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

            $this->error();
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids=''){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    $params['updatetime'] = time();
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->model->where(['id'=>$row['id']])->delete();
        $this->success();
    }

}
